package com.lkm.app_ui.ui;


import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.entity.UserVipOrderInfo;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.GsonHelp;
import com.lkm.app_ui.help.QRCodeUtil;
import com.lkm.app_ui.help.TaskHelp;
import com.lkm.app_ui.m.fun.DelegatePayTask;
import com.lkm.app_ui.m.fun.FunModule;
import com.lkm.app_ui.m.fun.OnPayEvent;
import com.lkm.app_ui.m.fun.OnWeightHoldEvent;
import com.lkm.app_ui.m.vip.OnVipEvent;
import com.lkm.app_ui.m.vip.VipInfo;
import com.lkm.app_ui.m.vip.VipModule;
import com.lkm.app_ui.ui.sale.SaleContract;
import com.lkm.comlib.Config;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.CTaskExecutor;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m_imple.steelyarddata.OnOrderUpStateEvent;
import com.lkm.market2_0.netapi.Api;

import androidx.annotation.Nullable;

import java.util.Map;


public class VipOrderFixFragment extends MBaseFragment {


    private SaleContract.Presenter presenter;

    private SalePrint salePrint = new SalePrint();

    public static VipOrderFixFragment getInstance() {
        VipOrderFixFragment f    = new VipOrderFixFragment();
        Bundle              data = new Bundle();

        f.setArguments(data);
        return f;
    }

    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_sec_pay_tips_success;
    }

    String      qrCode = "";
    String      print  = "";
    OrderEntity orderEntity;
    private OnPayEvent lastOnPayEvent;

    VipInfo newVipInfoTemp;

    VipInfo orderNewVipInfo;

    TextView tv_title_ordertips;
    TextView tv_title_viptips;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_title_ordertips = ((TextView) findViewById(R.id.tv_title_ordertips));
        tv_title_viptips = ((TextView) findViewById(R.id.tv_title_viptips));

        RunTimeData.PrintVipOrderInfo = null;

        presenter = SaleContract.presenter;

        try {
            lastOnPayEvent = AppConst.getModuleManager().peekModule(FunModule.class).lastPayInfo();
            orderEntity = lastOnPayEvent.getOrderEntity();
        } catch (Exception e) {
        }
        //TODO:这里需要研究 现金支付，通知给
        //P.p("Bill-> VipOrderFixFragment -> onViewCreated->lastOnPayEvent:" + lastOnPayEvent + ",orderEntity:" + orderEntity);
        if (lastOnPayEvent == null || orderEntity == null) {
            RouterUINavigation.getInstance().dismiss(VipOrderFixFragment.this);
            return;
        }


        qrCode = com.lkm.market2_0.m_imple.steelyardserver.server.Config.createQrCode(RunTimeData.steelyardInfo, orderEntity.orderNum);
        print = salePrint.cretePrintContent(orderEntity, SteelardHelp.formatMoney(orderEntity.totalPrice), orderEntity.getGoods(), orderEntity.createTime, RunTimeData.steelyardInfo, qrCode);

        joinPageUnitPrice = AppConst.getModuleManager().peekModule(FunModule.class).getCurUnitPrice();

        CreateQR createQR = new CreateQR();
        createQR.setParam(new Object[]{qrCode});
        createQR.action();
        createQR.execTask();

        loopD();

        reOnKeyEvent();
        regOnWeightHoldEvent();
        reVipEvent();
        regOrderUpState();

        PlayBeepEvent.send(PlayBeepEvent.TYPE_paySuccess);

        if (RunTimeData.steelyardInfo.isAutoPrintSuccessOrder()) {
            printOrder(false);
        }

        viewVipInfoTips();
    }

    boolean orderisUpSuccess     = false;
    boolean isUpVipInfoToOrderOK = false;

    private void regOrderUpState() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnOrderUpStateEvent>() {
            @Override
            public void onReceiver(OnOrderUpStateEvent data) {
                if (data.getState() == 0) {

                    orderisUpSuccess = true;
                    if (isUpVipInfoToOrderOK)
                        return;


                    if (newVipInfoTemp != null)
                        tryUpVipInfoToOrder(newVipInfoTemp);

                    viewVipInfoTips();

                    tv_title_ordertips.setVisibility(View.GONE);
                } else {
                    //TODO:可在这里过滤掉
                    if (DelegatePayTask.PayType_WVip == RunTimeData.tmpPayType || DelegatePayTask.PayType_StaticDelegate == RunTimeData.tmpPayType) {
                        tv_title_ordertips.setVisibility(View.GONE);
                    } else tv_title_ordertips.setVisibility(View.VISIBLE);
                }
                if (data.getState() == 1) {
                    tv_title_ordertips.setText("订单正在提交中");
                } else if (data.getState() == 2) {
                    tv_title_ordertips.setText("订单正在提交中");
                } else if (data.getState() == 3) {
                    tv_title_ordertips.setText("订单提交失败");
                }
            }

            @Override
            public Class<OnOrderUpStateEvent> getBusEventClass() {
                return OnOrderUpStateEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    public void viewVipInfoTips() {
        if (RunTimeData.steelyardExtData.payOnlineInfo.isUsbVipSystem) {
            tv_title_viptips.setVisibility(View.VISIBLE);
            VipInfo orderVipInfo = getOrderVipInfo();
            if (orderVipInfo != null) {
                String tips = "刷卡成功，会员号：" + orderVipInfo.getVipNo();
                tv_title_viptips.setText(Html.fromHtml("<font color='red'>" + tips + "</font>"));
            } else {
                if (RunTimeData.tmpPayType == DelegatePayTask.PayType_StaticDelegate || RunTimeData.tmpPayType == DelegatePayTask.PayType_WVip)
                    tv_title_viptips.setVisibility(View.GONE);
                else
                    tv_title_viptips.setText("如需会员卡积分补刷，请刷会员卡");
            }
        } else {
            tv_title_viptips.setVisibility(View.GONE);
        }
    }

    private void reVipEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnVipEvent>() {
            @Override
            public void onReceiver(OnVipEvent data) {
                VipInfo newVipInfo = newVipInfoTemp = data.getVipInfo();
                if (newVipInfo != null) {

                    data.setIntercepted(true);

                    tryUpVipInfoToOrder(newVipInfo);
                }
            }

            @Override
            public Class<OnVipEvent> getBusEventClass() {
                return OnVipEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    private VipInfo getOrderVipInfo() {
        return orderNewVipInfo != null ? orderNewVipInfo : lastOnPayEvent.getVipInfo();
    }

    private void tryUpVipInfoToOrder(VipInfo newVipInfo) {
        if (newVipInfo == null) return;
        if (!orderisUpSuccess) {
            AppUIHelp.tryShowTipsSHORT("订单提交中，会员信息等待提交...");
            return;
        }
        TaskHelp.cancelById(VipOrderFixTask.class.getName());
        VipOrderFixTask vipOrderFixTask = new VipOrderFixTask(newVipInfo);
        vipOrderFixTask.action();
        vipOrderFixTask.execTask();
    }

    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);

                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_PAY ||
                            data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_VipW ||
                            data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_VipCard ||
                            data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_DelegatePay
                    ) {

                        printOrder(false);

                    } else {

                        RouterUINavigation.getInstance().dismiss(VipOrderFixFragment.this);
                    }
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private boolean hasOrderVipInfo() {
        return isUpVipInfoToOrderOK;
    }

    private boolean upVipInfoToOrderAfterPrint = false;


    private void printOrder(boolean canNotVip) {
        if (orderEntity == null) {
            ViewUIHelp.showTipsLong(getActivity(), "无订单打印");
            return;
        }


        if (RunTimeData.steelyardExtData.payOnlineInfo.isUsbVipSystem) {

            if (RunTimeData.isPrint_vip() && !hasOrderVipInfo()) {


                VipInfo vipInfo = getOrderVipInfo();
                do {
                    if (vipInfo == null) break;

                    if (canNotVip) break;


                    upVipInfoToOrderAfterPrint = true;

                    if (TaskHelp.getTask(VipOrderFixTask.class.getName()) != null) break;

                    tryUpVipInfoToOrder(vipInfo);
                    return;
                } while (true);

            }
        }

        if (SaleFragment.saleFragment != null) {
            try {
                SaleFragment.saleFragment.createPrintInfo(orderEntity);
                SaleFragment.saleFragment.printOrder();
            } catch (Exception e) {
            }
        }

        if (presenter != null) {
            if (orderEntity.payTypeName == null || orderEntity.payTypeName.length() < 1) {
                orderEntity.payTypeName = "现金支付";
                RunTimeData.orderEntity.payTypeName = "现金支付";
            }
            presenter.printOrder(presenter.createPrintInfo(orderEntity));
        }
    }


    private double joinPageUnitPrice = 0;


    private void regOnWeightHoldEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnWeightHoldEvent>() {
            @Override
            public Class<OnWeightHoldEvent> getBusEventClass() {
                return OnWeightHoldEvent.class;
            }

            @Override
            public void onReceiver(OnWeightHoldEvent data) {


                if (RunTimeData.steelyardExtData.payOnlineInfo.isUsbVipSystem)
                    if (joinPageUnitPrice == data.getWeightChangeInfo().getUnitPrice()) {

                        return;
                    }


                RouterUINavigation.getInstance().dismiss(VipOrderFixFragment.this);
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    private void loopD() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    cjs--;
//                    ((TextView) findViewById(R.id.tv_tips)).setText(cjs + "秒后关闭\n打印票据：\"支付打印\";\n关闭界面：按\"功能选择\"键");

                    ((TextView) findViewById(R.id.tv_tips)).setText(Html.fromHtml(
                            cjs + "秒后关闭<br/>打印票据：\"支付打印\";" +
                                    "<br/><font color='red'>关闭界面：按\"功能选择\"键 </font>"
                    ));

                    if (cjs == 0) {
                        RouterUINavigation.getInstance().dismiss(VipOrderFixFragment.this);
                    } else {
                        loopD();
                    }
                } catch (Exception e) {
                }
            }
        }, 1 * 1000);
    }

    private int cjs = 180;

    protected class CreateQR extends TaskAdapter<Object[], Void, Bitmap> {

        public CreateQR() {
            super(new CTaskExecutor<Object[], Void, Bitmap>(Config.getTaskExecutor(), Looper.getMainLooper()), CreateQR.class.getName(), MyApplication.getInstance().getTaskManager2());
        }


        @Override
        public void doExecuting(Object[] param) {
            super.doExecuting(param);

            mTaskExecutor.executorDoAsyncExecuting(new RunnablePR<Object[], Void>() {
                @Override
                public Void run(Object[] objects) {
                    complete(onExecuting(objects));
                    return null;
                }
            }, param);
        }

        public Bitmap onExecuting(Object[] param) {

            int    ip       = -1;
            String orderurl = (String) param[++ip];
            Bitmap bitmap   = QRCodeUtil.createImage(orderurl, 400, 400);
            return bitmap;//ResponEntity.fromJson(Api.order_add(c,datas,this),AddOrderResult.class);
        }

        @Override
        public void onFinish(Bitmap bitmap) {
            super.onFinish(bitmap);
            if (isExit()) return;

            String printTable = print;


            if (printTable == null) printTable = "";

            int           printTableLength = printTable.length();
            StringBuilder stringBuilder    = new StringBuilder();
            int           count            = 0;
            for (int i = 0; i < printTableLength; i++) {
                String it = printTable.substring(i, i + 1);
                count += SalePrint.getCharWidth(it);
//                System.out.println(SaleFragment.getCharWidth(it)+"     "+it);
                stringBuilder.append(it);
                if (count >= 32) {
                    count = 0;
                    stringBuilder.append("\n");
                }

            }
            String orderInfoStr = stringBuilder.toString();


            try {
                ImageView img_qr = (ImageView) findViewById(R.id.img_qr);
                img_qr.setImageBitmap(bitmap);
            } catch (Exception e) {
            }
            ((TextView) findViewById(R.id.tv_printTable)).setText(orderInfoStr);

        }
    }


    private class VipOrderFixTask extends TaskAdapter<Void, String, ResponEntity<UserVipOrderInfo>> {

        private VipInfo upvipInfo;

        public VipOrderFixTask(VipInfo upvipInfo) {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), VipOrderFixTask.class.getName(), AppConst.getTaskManager2());
            this.upvipInfo = upvipInfo;
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            ViewUIHelp.showProgressBar(getActivity(), "提交会员信息...", VipOrderFixTask.class.getName());
        }

        @Override
        public void doExecuting(Void param) {
            super.doExecuting(param);
            mTaskExecutor.executor(new Runnable() {
                @Override
                public void run() {
                    try {
                        String json = Api.set_points(RunTimeData.steelyardInfo.steelyardMac, "" + RunTimeData.steelyardInfo.getOrg(), orderEntity.orderNum, upvipInfo.getVipNo(), VipOrderFixTask.this);
                        ResponEntity<UserVipOrderInfo> responEntity = ResponEntity.fromJson(json,
                                UserVipOrderInfo.class, "");
                        try {
                            responEntity.getData().json = GsonHelp.fromJson(json, JsonObject.class);
                            responEntity.getData().json = responEntity.getData().json.get("data").getAsJsonObject();
                        } catch (Exception e) {
                        }
                        complete(responEntity);
                    } catch (Exception e) {
                        cancel();
                    }

                }
            });
        }

        @Override
        public void onFinish(ResponEntity<UserVipOrderInfo> re) {
            super.onFinish(re);
            ViewUIHelp.disProgressBar(VipOrderFixTask.class.getName());
            if (re.isSuccess()) {
                orderNewVipInfo = upvipInfo;
                RunTimeData.PrintVipOrderInfo = re.getData();
                isUpVipInfoToOrderOK = true;
                viewVipInfoTips();

                VipInfo orderVipInfo = getOrderVipInfo();
                if (orderVipInfo != null) {
                    String tips = "刷卡成功，会员号：" + orderVipInfo.getVipNo();
                    AppUIHelp.tryShowTipsLong(tips);
                }
//                new HandleDialog().show(getActivity(), re.getMsg(), OnSteelyardKeyEvent.KEYCODE_9, "确定（按9）", new Runnable() {


//                        RouterUINavigation.getInstance().dismiss(VipOrderFixFragment.this);


                if (upVipInfoToOrderAfterPrint) {
                    upVipInfoToOrderAfterPrint = false;
                    printOrder(true);
                }
            } else {
                AppUIHelp.tryShowTipsLong(re.getMsg());
//                ViewUIHelp.showTips(getActivity(), re.getMsg());
            }
        }

        @Override
        public void onCancel() {
            super.onCancel();
            ViewUIHelp.disProgressBar(VipOrderFixTask.class.getName());
        }
    }

    @Override
    protected boolean configIsLockKey() {

        return !true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        VipModule vipModule = AppConst.getModuleManager().peekModule(VipModule.class);
        if (vipModule != null)
            vipModule.exitVip();
    }
}
